package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import model.GroceryListDao;
import model.HistoryItem;

/**
 * The HistoryPanel for displaying the history
 * @author Lawrence Grass
 */
@SuppressWarnings("serial")
public class HistoryPanel extends JPanel 
						  implements ActionListener{
	
	private GroceryListFrame frame;
	
	private JPanel historyView;
	
	private GroceryListDao dao;
	
	private int largestSizeItem = 0;
	
	public HistoryPanel(GroceryListFrame frame, GroceryListDao dao){
		super();
		this.dao = dao;
		this.frame = frame;
		this.setLayout(new BorderLayout());
		
		listSetup();
		JScrollPane sp = new JScrollPane(historyView);
		sp.setPreferredSize(new Dimension(380, 550));
		this.add(sp);
		
		//sets up the controls to manipulate the list
		this.add(controlsSetup(), BorderLayout.SOUTH);
	}
	
	/**
	 * helper method for the list panel
	 * @return the list panel
	 */
	private JPanel listSetup(){
		historyView = new JPanel();
		refreshItemsList();
		return historyView;
	}
	
	/**
	 * helper method for the controls panel
	 * @return the controls panel
	 */
	private JPanel controlsSetup(){
		JPanel controlsPanel = new JPanel();
		controlsPanel.setPreferredSize(new Dimension(200, 50));
		controlsPanel.setBackground(Color.gray);
		JButton back = new JButton("Go Back ");
		back.addActionListener(this);
		back.setPreferredSize(new Dimension(120, 20));
		controlsPanel.add(back);
		
		return controlsPanel;
	}
	
	public void refreshItemsList(){
		largestSizeItem = 0;
		historyView.removeAll();
		try {
			List<HistoryItem> list = dao.getHistory();
			for(HistoryItem item: list){
				JPanel row = new JPanel();
				row.setPreferredSize(new Dimension(400, 40));
				if(item.getItem().length() > largestSizeItem)
				{
					 largestSizeItem = item.getItem().length();
				}
				if(item.getItem().length() > 10)
				{
					row.setPreferredSize(new Dimension((400 + item.getItem().length() * 4), 40));
				}
				JLabel history = new JLabel(item.toString());
				row.add(history);
				historyView.add(row);
				historyView.setPreferredSize(new Dimension(380, list.size() * 50));
				if(largestSizeItem > 20)
				{
					historyView.setPreferredSize(new Dimension((400 + largestSizeItem * 4), list.size() * 50));
				}
				
			}
			
		} catch (Exception e) {
			//Do nothing?
			e.printStackTrace();
		}
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		frame.refreshCards();
		frame.goMain();
	}
}
